package com.yh.workbill.ui.addworkbill;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.yh.workbill.App;
import com.yh.workbill.R;
import com.yh.workbill.base.BaseActivity;
import com.yh.workbill.databinding.ActivityAddWorkBillBinding;
import com.yh.workbill.databinding.LayoutHeadBinding;
import com.yh.workbill.db.Company;
import com.yh.workbill.db.CompanyDao;
import com.yh.workbill.db.UnitCompany;
import com.yh.workbill.db.UnitCompanyDao;
import com.yh.workbill.event.AddWorkBillEvent;
import com.yh.workbill.model.WorkBill;
import com.yh.workbill.model.WorkDevices;
import com.yh.workbill.ui.addworkbill.mvp.AddWorkBill_Presenter;
import com.yh.workbill.ui.addworkbill.mvp.AddWorkBill_View;
import com.yh.workbill.utils.Utils;
import com.yh.workbill.view.BottomCompanySelectDialog;
import com.yh.workbill.view.BottomDevicesSelectDialog;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProviders;

public class AddWorkBillActivity extends BaseActivity implements AddWorkBill_View {

    private ActivityAddWorkBillBinding binding;
    private AddWorkBillViewModel viewModel;
    private LiveData<List<Company>> findAllCompanys;
    private LiveData<List<UnitCompany>> findAllUnitCompanys;
    private AddWorkBill_Presenter presenter;
    private BottomCompanySelectDialog bottomCompanySelectDialog;
    private BottomDevicesSelectDialog bottomDevicesSelectDialog;
    private TimePickerView pvTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_work_bill);
    }

    @Override
    public void initJetPack(@Nullable Bundle savedInstanceState) {
        viewModel = ViewModelProviders.of(this).get(AddWorkBillViewModel.class);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initObserve(@Nullable Bundle savedInstanceState) {
        findAllCompanys = viewModel.getFindAllCompanys();
        findAllUnitCompanys = viewModel.getFindAllUnitCompanys();
        findAllCompanys.observe(this, companies -> {
            if (companies.size() > 0) {
                binding.llSelectCompany.setVisibility(View.VISIBLE);
            } else {
                binding.llSelectCompany.setVisibility(View.GONE);
            }
        });

        findAllUnitCompanys.observe(this, unitCompanies -> {
            if (unitCompanies.size() > 0) {
                binding.llUnitCompany.setVisibility(View.VISIBLE);
            } else {
                binding.llUnitCompany.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public void initBaseSetting(@Nullable Bundle savedInstanceState) {
        presenter = new AddWorkBill_Presenter(this);
        this.getLifecycle().addObserver(presenter);
    }

    @Override
    public void initClick(@Nullable Bundle savedInstanceState) {
        LayoutHeadBinding layoutHead = binding.layoutHead;
        layoutHead.llBlack.setOnClickListener(v -> back());
        layoutHead.setTitle("添加工作单");

        binding.llSelectCompany.setOnClickListener(v -> {
            List<Company> value = findAllCompanys.getValue();
            if (value == null || value.size() <= 0) {
                return;
            }
            ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
                List<String> temp = new ArrayList<>();
                for (Company bean : value) {
                    temp.add(bean.getCompany_name());
                }
                ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                    if (bottomCompanySelectDialog == null) {
                        bottomCompanySelectDialog = new BottomCompanySelectDialog(AddWorkBillActivity.this, temp);
                    }
                    bottomCompanySelectDialog.show();
                    bottomCompanySelectDialog.setOnSelect(new BottomCompanySelectDialog.OnSelect() {
                        @Override
                        public void onSelect(String value) {
                            binding.etCompany.setText(value);
                            bottomCompanySelectDialog = null;
                        }

                        @Override
                        public void onDismiss() {
                            bottomCompanySelectDialog = null;
                        }
                    });
                });
            });
        });

        binding.llUnitCompany.setOnClickListener(v -> {
            List<UnitCompany> value = findAllUnitCompanys.getValue();
            if (value == null || value.size() <= 0) {
                return;
            }
            ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
                List<String> temp = new ArrayList<>();
                for (UnitCompany bean : value) {
                    temp.add(bean.getUse_name());
                }
                ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                    if (bottomCompanySelectDialog == null) {
                        bottomCompanySelectDialog = new BottomCompanySelectDialog(AddWorkBillActivity.this, temp);
                    }
                    bottomCompanySelectDialog.show();
                    bottomCompanySelectDialog.setOnSelect(new BottomCompanySelectDialog.OnSelect() {
                        @Override
                        public void onSelect(String value) {
                            binding.etUse.setText(value);
                            bottomCompanySelectDialog = null;
                        }

                        @Override
                        public void onDismiss() {
                            bottomCompanySelectDialog = null;
                        }
                    });
                });
            });
        });

        binding.btnAdd.setOnClickListener(v -> {

            String company_name = binding.etCompany.getText().toString().trim();
            if (TextUtils.isEmpty(company_name)) {
                Utils.ShowToas(AddWorkBillActivity.this, "请输入/选择公司");
                return;
            }

            String work_unit = binding.etUse.getText().toString().trim();
            if (TextUtils.isEmpty(work_unit)) {
                Utils.ShowToas(AddWorkBillActivity.this, "请输入/选择租借单位");
                return;
            }

            if (viewModel.getCurrentWorkDevices().getValue() == null) {
                Utils.ShowToas(AddWorkBillActivity.this, "请选择用工设备");
                return;
            }
            String work_device = viewModel.getCurrentWorkDevices().getValue().getName();
            if (TextUtils.isEmpty(work_device) || work_device.equals("请选择用工设备")) {
                Utils.ShowToas(AddWorkBillActivity.this, "请选择用工设备");
                return;
            }

            String work_time = binding.tvTime.getText().toString().trim();
            if (TextUtils.isEmpty(work_time) || work_time.equals("请选择用工时间")) {
                Utils.ShowToas(AddWorkBillActivity.this, "请选择用工时间");
                return;
            }

            String work_car_number = binding.etWorkCarNumber.getText().toString().trim();
            if (TextUtils.isEmpty(work_car_number)) {
                Utils.ShowToas(AddWorkBillActivity.this, "请输入设备车牌");
                return;
            }

            double work_use_time = Double.valueOf(binding.etWorkTime.getText().toString().trim());
            if (TextUtils.isEmpty(String.valueOf(work_use_time))) {
                Utils.ShowToas(AddWorkBillActivity.this, "请输入使用时长");
                return;
            }

            String work_content = binding.etWorkContent.getText().toString().trim();
            double devices_price = viewModel.getCurrentWorkDevices().getValue().getDevices_price();


            WorkBill bill = new WorkBill();
            bill.setWork_time(work_time);
            bill.setWork_unit(work_unit);
            bill.setWork_content(work_content);
            bill.setWork_car_number(work_car_number);
            bill.setWork_device(work_device);
            bill.setWork_time_price(devices_price);
            bill.setWork_use_time(work_use_time);
            bill.setCompany_name(company_name);
            presenter.addWorkBill(bill);
        });

        binding.llDevices.setOnClickListener(v -> httpDevices());

        binding.llSelectTime.setOnClickListener(v -> pvTime.show());

        binding.clDevices.setOnClickListener(v -> httpDevices());
        binding.clTime.setOnClickListener(v -> pvTime.show());
    }

    @Override
    public void initDefaultMethod(@Nullable Bundle savedInstanceState) {
        initTimePicker();
    }

    @Override
    public void addWorkBillCalback(String msg, String company, String unitCompany, WorkBill data) {
        if (!TextUtils.isEmpty(msg)) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
        binding.etCompany.setText("");
        binding.etCompany.setHint("请输入/选择公司名称");
        binding.etUse.setText("");
        binding.etUse.setHint("请输入/选择租借单位");
        binding.tvDevices.setText("请选择用工设备");
        binding.tvTime.setText("请选择用工时间");
        binding.etWorkCarNumber.setText("");
        binding.etWorkCarNumber.setHint("请输入设备车牌");
        binding.etWorkTime.setText("");
        binding.etWorkTime.setHint("请输入使用时长");
        binding.etWorkContent.setText("");
        binding.etWorkContent.setHint("请输入工作内容");

        ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
            CompanyDao companyDao = App.appDataBase.getCompanyDao();
            Company companyDB = companyDao.getCompany(company);
            if (companyDB == null || companyDB.getCompany_name().equals("")) {
                companyDao.add(new Company(company, "", ""));
            }

            UnitCompanyDao unitCompanyDao = App.appDataBase.getUnitCompanyDao();
            UnitCompany unitComanyDB = unitCompanyDao.getUnitComany(unitCompany);
            if (unitComanyDB == null || unitComanyDB.getUse_name().equals("")) {
                unitCompanyDao.add(new UnitCompany(unitCompany));
            }
        });
        //发消息处理主页数据
        EventBus.getDefault().post(new AddWorkBillEvent(data));
    }

    @Override
    public void addWorkBillFail(String err) {
        if (!TextUtils.isEmpty(err)) {
            Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getAllDevices(List<WorkDevices> data) {
        if (bottomDevicesSelectDialog == null) {
            bottomDevicesSelectDialog = new BottomDevicesSelectDialog(AddWorkBillActivity.this, data);
        }
        bottomDevicesSelectDialog.show();
        bottomDevicesSelectDialog.setOnSelect(new BottomDevicesSelectDialog.OnSelect() {
            @Override
            public void onSelect(WorkDevices workDevices) {
                viewModel.getCurrentWorkDevices().setValue(workDevices);
                binding.tvDevices.setText(workDevices.getName());
            }
        });
    }

    @Override
    public void httpDevices() {
        presenter.getDevices();
    }

    @Override
    public void clearData() {

    }

    @Override
    public void back() {
        finish();
    }

    @Override
    public void showTasot(String message) {
        if (!TextUtils.isEmpty(message)) {
            Utils.ShowToas(AddWorkBillActivity.this, message);
        }
    }

    @Override
    public void showDialog(String content, boolean isCancelable) {
        showLoaddingDialog(content, isCancelable);
    }

    @Override
    public void hideDialog() {
        hideLoaddingDialog();
    }


    private void initTimePicker() {//Dialog 模式下，在底部弹出
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(2017, 0, 1);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = df.format(new Date());
        String[] split = currentTime.split("-");

        endDate.set(Integer.valueOf(split[0]), Integer.valueOf(split[1]) - 1, Integer.valueOf(split[2]));
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                binding.tvTime.setText(Utils.getTime(date));
            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setSubmitColor(getResources().getColor(R.color.colorAccent))//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pvTime != null) {
            pvTime.dismiss();
        }
    }
}
